import { CameraView, CameraType, useCameraPermissions } from 'expo-camera';
import { useState, useEffect } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Linking } from 'react-native';
import Headers from '@/app/components/header/Headers'
import { useRouter } from 'expo-router';
import * as Haptics from 'expo-haptics';
import { useNavigation, useRoute } from "@react-navigation/native";
export default function qRScanner() {
  const [facing, setFacing] = useState<CameraType>('back');
  const [permission, requestPermission] = useCameraPermissions();
  const [isScanning, setIsScanning] = useState(true);
  const navigation = useNavigation<any>();
  const router = useRouter();
  const route:any = useRoute();

  useEffect(() => {
    if (permission && !permission.granted) {
      requestPermission();
    }
  }, [permission, requestPermission])

  if (!permission) {
    // Camera permissions are still loading.
    return <View />;
  }

  if (!permission.granted) {
    // Camera permissions are not granted yet.
    return (
      <View style={styles.container}>
        <Headers title="扫一扫" centerColor={'#fff'} leftIcon={require('@/assets/images/icon/back2.png')} barStyle={1} backgroundColor={'rgba(0,0,0,0)'} setTranslucent={true} />
        <View style={styles.permissionContainer}>
          <Text style={styles.message}>需要相机权限才能使用扫码功能</Text>
          <TouchableOpacity style={styles.permissionButton} onPress={requestPermission}>
            <Text style={styles.permissionButtonText}>授权相机权限</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  function toggleCameraFacing() {
    setFacing(current => (current === 'back' ? 'front' : 'back'));
  }

  return (
    <View style={styles.container}>
      {/* <StatusBar barStyle="light-content" backgroundColor="rgba(0, 0, 0, 0.8)" /> */}
      <Headers title="扫一扫" centerColor={'#fff'} leftIcon={require('@/assets/images/icon/back2.png')} barStyle={1} backgroundColor={'rgba(0,0,0,0)'} setTranslucent={true} />
      <CameraView style={styles.camera} facing={facing}
        barcodeScannerSettings={{
          barcodeTypes: ["qr"],
        }}
        onBarcodeScanned={isScanning ? async (data) => {
          console.log(JSON.stringify(data.data));
          console.log('扫描成功', `扫描到的内容：${data.data}`);
          
          // 暂停扫描以防止重复触发
          setIsScanning(false);
          
          const scannedContent = data.data;
          // 触发成功反馈
          await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
          // 检查是否为 HTTP 或 HTTPS 链接
          if (scannedContent.startsWith('http://') || scannedContent.startsWith('https://')) {
            // 跳转到 webview 页面，并携带链接参数
            navigation.replace('pages/webview/webview', { url: scannedContent});
          } else {
            // 使用路由状态传递数据回上一页
            // 在 Expo Router 中，我们可以通过将数据存储在全局对象中来实现
            // 实际项目中应考虑使用更健壮的状态管理方案
            // global._qrScanData = scannedContent;
            // router.back();
            let params = route.params||{};
            params.callback&&params.callback(scannedContent);
            navigation.goBack();
          }
        } : undefined}
      />

      {/* 扫描框 */}
      <View style={styles.scanFrame}>
        <View style={styles.scanCorner} />
        <View style={[styles.scanCorner, styles.topRight]} />
        <View style={[styles.scanCorner, styles.bottomLeft]} />
        <View style={[styles.scanCorner, styles.bottomRight]} />
      </View>

      {/* 提示文字 */}
      <View style={styles.hintContainer}>
        <Text style={styles.hintText}>将二维码放入框内进行扫描</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
  },
  permissionContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  message: {
    textAlign: 'center',
    paddingBottom: 20,
    color: 'white',
    fontSize: 16,
  },
  permissionButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 30,
    paddingVertical: 12,
    borderRadius: 8,
  },
  permissionButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '600',
  },
  camera: {
    flex: 1,
  },
  navButton: {
    padding: 8,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
  },
  scanFrame: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    width: 250,
    height: 250,
    marginTop: -125,
    marginLeft: -125,
  },
  scanCorner: {
    position: 'absolute',
    width: 20,
    height: 20,
    borderColor: '#00ff00',
    borderWidth: 3,
    borderTopWidth: 3,
    borderLeftWidth: 3,
    borderRightWidth: 0,
    borderBottomWidth: 0,
  },
  topRight: {
    top: 0,
    right: 0,
    borderBottomWidth: 0,
    borderRightWidth: 3,
    borderTopWidth: 3,
    borderLeftWidth: 0,
  },
  bottomLeft: {
    bottom: 0,
    left: 0,
    borderTopWidth: 0,
    borderRightWidth: 0,
    borderBottomWidth: 3,
    borderLeftWidth: 3,
  },
  bottomRight: {
    bottom: 0,
    right: 0,
    borderTopWidth: 0,
    borderRightWidth: 3,
    borderBottomWidth: 3,
    borderLeftWidth: 0,
  },
  hintContainer: {
    position: 'absolute',
    bottom: 100,
    left: 0,
    right: 0,
    alignItems: 'center',
  },
  hintText: {
    color: 'white',
    fontSize: 16,
    textAlign: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
  },
});
